<template>
  <div class="h-full flex flex-col overflow-auto">
    <a-radio-group v-model:value="activeKey" size="large" button-style="solid" class="w-full flex mb-4 mt-2 truncate">
      <a-radio-button v-for="item in dictOutList" :key="item.dictOutpMatterId" :value="item.dictOutpMatterId"
        >{{ item.matterName }} {{ item.quantity }}人</a-radio-button
      >
    </a-radio-group>
    <a-form class="flex-1 overflow-hidden flex" :model="registerState">
      <a-card class="w-3/5 h-full" :body-style="{ height: '100%' }">
        <div class="flex flex-col overflow-hidden">
          <BaseTitle title="患者信息" class="!pr-0" />
          <div class="overflow-auto mt-3">
            <PatientInfoForm
              ref="patientInfoForm"
              v-model:value="patientState"
              form-class="pr-1.5"
              item-class="w-1/3"
              :exclude-item="['收费标准']"
              patient-type="普通加预约患者"
              @loaded="patientInfoLoading = false"
              @scan-code="onScanCode"
            />
          </div>
        </div>
        <div v-if="systemConfig.isHistoryList" class="mt-5">
          <BaseTable
            bordered
            column-code="000283"
            :exclude-columns="systemConfig.isInterconnection ? [] : ['yqmc']"
            :loading="loading"
            :scroll="{ x: 1500 }"
            :height="150"
            :data-source="tableData"
            :pagination="false"
          >
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex == 'xh'">
                {{ index + 1 }}
              </template>
            </template>
          </BaseTable>
        </div>
      </a-card>
      <div class="ml-2 w-2/5 h-full overflow-auto flex flex-col">
        <a-card class="flex-1">
          <BaseTitle title="挂号" class="">
            <SelectChargeStandard v-if="systemConfig.isChargeStandard" v-model:value="registerState.chargeStandardId" class="ml-9 flex-1" select-first />
          </BaseTitle>
          <div class="flex flex-wrap 2xl:mt-4 mt-1">
            <a-form-item label="类别" class="w-1/3" required>
              <SelectRegistType v-model:value="registerState.ghlbid" :disabled="!!registerState.empId" class="w-full" @change="onSelectCategory" />
            </a-form-item>
            <a-form-item label="科室" class="w-1/3 pl-2" required>
              <a-select
                v-model:value="registerState.ksdm"
                :disabled="!!registerState.empId"
                placeholder="请选择"
                :options="departmentList"
                :field-names="{ label: 'ksmc', value: 'ksdm' }"
                @select="onSelectDepartment"
              />
            </a-form-item>
            <a-form-item class="w-1/3 pl-12">
              <a-radio-group v-model:value="registerState.czfz">
                <a-radio :value="0">初诊</a-radio>
                <a-radio :value="1">复诊</a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
          <!-- 选择医生 -->
          <a-form-item label="医生" class="mb-1 w-1/3" :label-col="{ style: { width: '48px' } }">
            <a-input v-model:value="doctorSearchKey" placeholder="搜索医生" :disabled="doctorList.length === 0" />
          </a-form-item>
          <a-carousel arrows class="w-full mb-2" :dots="false" :infinite="false">
            <template #prevArrow>
              <LeftOutlined class="!left-4 !text-base !text-gray-400 !bg-slate-100 z-10 rounded" />
            </template>
            <template #nextArrow>
              <RightOutlined class="!right-4 !text-base !text-gray-400 !bg-slate-100 z-10 rounded" />
            </template>
            <div v-for="(doctorChunk, index) in doctorChunkList" :key="index">
              <CheckTags v-model:value="registerState.empId" tag-key="empId" :data-source="doctorChunk" @select="onSelectDoctor">
                <template #renderItem="{ item }"> {{ item.empName }}{{ item?.numberQuantityLimit }}</template>
              </CheckTags>
            </div>
            <div v-if="doctorChunkList.length === 0" class="w-full h-12 text-disabled !flex items-center">暂无医生</div>
          </a-carousel>
          <div class="flex flex-wrap">
            <a-form-item label="费别" class="w-full cost-type" required :wrapper-col="{ style: { flex: '1' } }">
              <div class="max-h-20 overflow-auto">
                <CheckTags v-model:value="registerState.ghfbid" tag-key="ghfbid" tag-class="min-w-[180px]" :data-source="feeList" @select="onChangeFeeType">
                  <template #renderItem="{ item }"> {{ item.ghfb }}</template>
                </CheckTags>
              </div>
            </a-form-item>
            <a-form-item v-if="getSystemConfig('IS_DOCTOR_ASSISTANT') === '1' && systemConfig.isAssistance" label="医助" class="w-1/2">
              <SelectTable v-model:value="registerState.assistant1EmpName" type="员工" placeholder="请选择" @select="onSelectAssistant1" />
            </a-form-item>
            <!-- <a-form-item label="医助二" class="w-1/2">
              <SelectTable v-model:value="registerState.assistant2EmpName" type="员工" placeholder="请输入" @select="onSelectAssistant2" />
            </a-form-item> -->
            <a-divider dashed class="mt-2 mb-4" />

            <template v-if="systemConfig.isDisposePackage">
              <a-form-item label="处置套餐" class="w-1/2">
                <a-input v-model:value="registerState.tcName" placeholder="请选择" readonly allow-clear @click="suitOpen = true">
                  <template v-if="registerState.tcid" #suffix>
                    <CloseCircleFilled class="cursor-pointer text-gray-300" @click="onClearSuit" />
                  </template>
                </a-input>
              </a-form-item>
              <div class="w-1/2 flex justify-between pl-4">
                <a-form-item class="text-right"> 套餐金额：￥{{ formatAmount(registerState.tchjje) }}</a-form-item>
                <a-form-item class="text-right">
                  <span>
                    结算金额：<span class="text-red-500 font-bold">￥{{ formatAmount(registerState.tcjsje) }}</span>
                  </span>
                </a-form-item>
                <a-form-item class="">
                  <a-button type="primary" ghost :disabled="!registerState.tcid" @click="discountsOpen = true">套餐打折</a-button>
                </a-form-item>
              </div>
              <!-- 处置套餐明细 -->
              <!-- <PackageTable v-if="registerState.tcid" ref="packRef" :params="registerState" /> -->
            </template>
            <div class="flex items-center">
              <a-form-item v-if="systemConfig.isMedicalCardFee" label="病历本费">
                <a-switch v-model:checked="registerState.blbf" />
              </a-form-item>
              <a-form-item v-if="systemConfig.isInfoCardFee" label="信息卡费" class="ml-4">
                <a-switch v-model:checked="registerState.xxkf" />
              </a-form-item>
            </div>
            <a-form-item label="挂号备注" class="w-full mt-2">
              <a-textarea v-model:value="registerState.memo" :rows="3" placeholder="请输入" />
            </a-form-item>
          </div>
        </a-card>
        <div class="flex flex-col relative overflow-auto">
          <!-- 优惠 -->
          <!-- <CouponCard
            v-if="systemConfig.isCoupon"
            ref="couponRef"
            v-model:value="patientState.brId"
            :medical-price="registerState.ssje"
            class="mt-2"
            @success="onSuccessCoupon"
          /> -->
          <!-- <a-card class="mt-2">
            <BaseTitle title="分币误差" class="!mb-0">
              <span>
                分币：<span class="text-red-500 font-bold">￥{{ formatAmount(registerState.fbyh) }}</span>
              </span>
            </BaseTitle>
          </a-card> -->
          <div class="static bottom-0 w-full">
            <a-card class="mt-2">
              <div class="text-right mr-2">
                <div class="flex items-center justify-end mb-3">
                  <div class="mr-8 flex items-center">
                    <span class="mr-2">打印票据</span>
                    <a-switch v-model:checked="isPrintReceipt" />
                  </div>
                  <div class="flex items-center">
                    本次应收 <span class="text-3xl text-red-500 font-bold">￥{{ formatAmount(registerState.ysje) }}</span>
                  </div>
                </div>

                <div class="inline-flex items-center mr-4">打印挂号单<a-switch v-model:checked="appStore.IS_PRINT" class="ml-2" /></div>
                <a-button class="ml-2 w-28" size="large" :disabled="!patientState.brName" @click="savePatientInfo(true)">保存档案</a-button>
                <a-button class="ml-2 w-28" size="large" @click="onReset">重置</a-button>
                <!-- !registerState.ssje || -->
                <a-button type="primary" class="ml-2 w-28" size="large" :loading="chargeLoading" :disabled="!isCompleted" @click="savePatientInfo()">
                  {{ isArmy ? '挂号' : '收费' }}
                </a-button>
              </div>
            </a-card>
          </div>
        </div>
      </div>
    </a-form>
    <ChargeModal v-model:open="chargeOpen" :br-id="patientState.brId" :business-data="{ ysje: registerState.ysje }" @success="onChargeSuccess" />
    <SuitModal v-model:open="suitOpen" :dict-matter-id="activeKey" @success="onSelectTemplate" />
    <SuitDiscounts v-model:open="discountsOpen" :amount="registerState.tchjje" :discount-amount="registerState.tcjsje" @success="onDiscounts">
      {{ registerState.tcName }}
    </SuitDiscounts>
    <SignModal v-model:open="signOpen" :row-data="rowData" @success="onSuccessSignIn" />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import { chunk } from 'lodash-es'
import { LeftOutlined, RightOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import { post, get } from '@/utils/request'
import { formatAmount, getAgeUnit } from '@/utils/format'
import CheckTags from '@/components/CheckTags'
import { getSystemConfig } from '@/utils/systemConfig'
import cofirmModal from '@/utils/confirm'
import ChargeModal from '@/components/ChargeModal'
import useAppStore from '@/store/app'
// import CouponCard from '@/components/CouponCard'
import SignModal from '@/components/SignModal'
import SelectRegistType from '@/components/SelectRegistType'
// import useStore from '../../store'
import SuitModal from '../components/SuitModal.vue'
import SuitDiscounts from '../components/SuitDiscounts.vue'
// import PackageTable from '../components/PackageTable.vue'

// const userInfoStore = useStore()
const appStore = useAppStore()
const router = useRouter()

const isPrintReceipt = ref(true)
const patientInfoLoading = ref(true)
const suitOpen = ref(false)
const discountsOpen = ref(false)
const chargeOpen = ref(false)
const signOpen = ref(false)
const chargeLoading = ref(false)
const patientInfoForm = ref(null)

const patientState = ref({})
const registerState = ref({ ghlbid: null, czfz: 0, xxkf: false, blbf: false }) // czfz: 0,
const activeKey = ref('')
const couponId = ref('') // 优惠券的id
const couponPrice = ref('') // 抵用券金额
const memberId = ref('') // 会员id
const memberPrice = ref('') // 会员卡钱
const dictOutList = ref([])
const rowData = ref({})

watch(
  () => patientState.value?.brId,
  (val) => {
    registerState.value.czfz = patientState.value.czfz || registerState.value.czfz || 0
    if (patientState.value.yylsh) {
      router.push({
        path: '/out-registration/register',
        query: { ...route.query, id: patientState.value.brId, status: '1' }
      })
      setTimeout(() => getPatientInfo(), 300)
    }
    val ? getData() : (tableData.value = [])
    // registerState.value.czfz = patientState.value.czfz ?? 0
    // registerState.value.cmemo2 = patientState.value?.cmemo2
    // if (patientState.value.yylsh) {
    //   registerState.value.ksdm = patientState.value.ksdm
    //   registerState.value.ksdms = [patientState.value.ksdm]
    //   activeKey.value = patientState.value?.dictOutpMatterId
    //   registerState.value.memo = patientState.value.yymemo
    //   getDoctorList()
    // }
  }
)

// 切换就诊事项清空选中的处置套餐
watch(
  () => activeKey.value,
  () => {
    onClearSuit()
  }
)

const { loading, tableData, getData } = useTable({
  // url: '/outp/mzdj/getPatientHistoryRegistrationInformationList',
  url: getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1' ? '/outp/mzdj/getMedicalHistoryList' : '/outp/mzdj/getPatientHistoryRegistrationInformationList',
  formatParams: () => {
    return {
      brId: patientState.value?.brId,
      br_id: patientState.value?.brId
    }
  }
})

const onSelectCategory = (value) => {
  registerState.value.ghlb = value
  registerState.value.empId = ''
  registerState.value.empName = ''
  getDoctorList(false)
  getFeeList()
}

const onSelectDepartment = (value) => {
  registerState.value.oldKsdm = value
  registerState.value.ksdms = [value]
  registerState.value.ksdm = value
  getDoctorList()
}
const onSelectDoctor = (_, select) => {
  if (systemConfig.value.defaultChargeMode === '1') {
    getPriceItem(select)
    if (Object.keys(select).length > 0) {
      feeList.value = [select]
    } else {
      getFeeList()
    }
  } else if (systemConfig.value.defaultChargeMode === '2') {
    if (Object.keys(select).length > 0) {
      getDetailData()
    } else {
      getFeeList()
    }
  }
}
const getDetailData = async () => {
  const { data, code } = await post('/operation/opex/getEmpGHFBRegistered', {
    empId: registerState.value?.empId,
    pageNum: 1,
    pageSize: 999
  })
  if (code === 0) {
    feeList.value = data
    getPriceItem(data[0])
  }
}
const getPriceItem = (item) => {
  // const ksdm = item.ksdm || registerState.value.oldKsdm
  // registerState.value.ksdms = [ksdm]
  // registerState.value.ksdm = ksdm
  registerState.value.zlfybh = item.zlfybh
  registerState.value.ghfybh = item.ghfybh
}
// 获取科室
const departmentList = ref([])
const getDepartmentList = async () => {
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', { sfylks: '0' })
  if (code !== 0) return
  departmentList.value = data
  if (!registerState.value.ksdm && data.length > 0) {
    registerState.value.ksdm = departmentList.value[0]?.ksdm
    registerState.value.oldKsdm = departmentList.value[0]?.ksdm
    registerState.value.ksdms = [departmentList.value[0]?.ksdm]
  }
  getDoctorList()
}

//获取医生
const doctorList = ref([])
const doctorSearchKey = ref('')
const doctorChunkList = computed(() => {
  if (doctorSearchKey.value) {
    return chunk(
      doctorList.value.filter((item) => item.empName.includes(doctorSearchKey.value)),
      10
    )
  }
  return chunk(doctorList.value, 10)
})
const getDoctorList = async (isDelete = true) => {
  const params = {
    ksdm: registerState.value.ksdm,
    ghlbid: registerState.value.ghlbid
  }
  if (patientState.value.yylsh && isDelete) {
    delete params.ghlbid
  }
  const { code, data = [] } = await post('/outp/mzdj/getSchedulingDocterList', params)
  if (code !== 0) return
  doctorList.value = data
  // registerState.value.empId = patientState.value.empId
  if (doctorChunkList.value.length > 0) {
    const doctorItem = doctorChunkList.value.flat().find((i) => {
      return i.empId === patientState.value.empId
    })
    if (doctorItem) {
      registerState.value.empId = doctorItem ? doctorItem.empId : ''
      registerState.value.ghlbid = doctorItem ? doctorItem.ghlbId : ''
      onSelectDoctor('', doctorItem)
    }
  }
}

// 获取费别
const feeList = ref([])
const getFeeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getRegisterFee', {
    empId: registerState.value.empId,
    ghlbid: registerState.value.ghlbid
  })
  if (code !== 0) return
  if (data && data.length > 0) {
    feeList.value = data
    registerState.value = { ...registerState.value, ...data[0] }
  }
}
//选择套餐
const onSelectTemplate = (suit) => {
  registerState.value.tcid = suit.tcid
  registerState.value.tcName = suit.mc
  registerState.value.tchjje = suit.tcPrice
  registerState.value.tcjsje = suit.tcPrice
  // packRef.value.getPackData()
}
const onChangeFeeType = (_, type) => {
  registerState.value = { ...registerState.value, ...type }
}
const onDiscounts = (data) => {
  registerState.value.tcjsje = data
}
watch(
  [
    () => registerState.value.ghfybh,
    () => registerState.value.zlfybh,
    () => registerState.value.blbf,
    () => registerState.value.xxkf,
    () => registerState.value.chargeStandardId,
    () => registerState.value.ksdm,
    () => registerState.value.tcjsje
  ],
  () => {
    getReceivableMoney()
  }
)

// watch(
//   () => registerState.value.yhje,
//   () => getRealityMoney()
// )

// 选择优惠券
// const onSuccessCoupon = async (id, price, state) => {
//   if (state === 1) {
//     couponId.value = id
//     couponPrice.value = Number(price)
//   } else {
//     memberId.value = id
//     memberPrice.value = Number(price)
//   }
//   await getReceivableMoney()
// }

//计算应收
const getReceivableMoney = async () => {
  const { blbf, xxkf, chargeStandardId, ghfybh, ksdms, tchjje, tcid, zlfybh, tcjsje } = registerState.value
  if (!ghfybh) {
    registerState.value.ysje = 0
    registerState.value.ssje = 0
    registerState.value.fbyh = 0
    return
  }
  const { code, data, msg } = await post('/outp/mzdj/registeredReceivableCalculations', {
    blbf, //病历本费
    xxkf, //信息卡费
    chargeStandardId: systemConfig.value.isChargeStandard ? chargeStandardId : '', //收费标准编号
    zlfybh, //诊疗费编号
    ghfybh, //挂号费编号
    ksdms, //科室代码
    tchjje, //套餐合计金额
    tcjsje, //套餐结算金额
    tcid //套餐ID
  })
  if (code !== 0) return message.error(msg || '获取应收金额失败')
  registerState.value.ysje = data || 0
  // getRealityMoney()
}
//计算实收&分币
// const getRealityMoney = async () => {
//   const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
//     ysje: registerState.value.ysje || 0, //应收金额
//     yhje: registerState.value.yhje || 0,
//     patientCouponsId: couponId.value, // 优惠券id
//     offsetAmount: couponPrice.value // 抵用券金额
//   })
//   if (code !== 0) return message.error(msg || '获取实收金额失败')
//   registerState.value.ssje = data.ssje || 0
//   registerState.value.fbyh = data.fbwc || 0
// }
const onChargeSuccess = async (chargeData = {}) => {
  chargeLoading.value = true
  registerState.value.isChargeInformationcard = registerState.value.xxkf ? 1 : 0
  registerState.value.isChargeMedicalbook = registerState.value.blbf ? 1 : 0
  const { code, msg, jzbhs, pjhm } = await post(
    '/outp/mzdj/doRegister',
    {
      ...patientState.value,
      ...registerState.value,
      ...chargeData,
      brAge: getAgeUnit(patientState.value.brAge).brAge || 0,
      ghlbid: patientState.value.ghlbid ? patientState.value.ghlbid : registerState.value.ghlbid,
      dictOutpMatterId: activeKey.value,
      miFlag: 0,
      czfz: registerState.value?.czfz,
      fbyh: registerState.value.fbwc
      // vipno: memberId.value,
      // dyqzf: couponPrice.value, // 抵用券金额
      // dyqno: couponId.value // 抵用券id
    },
    { loading: true }
  )
  chargeLoading.value = false
  if (code !== 0) return message.error(msg || '挂号失败')
  message.success('挂号成功')
  chargeOpen.value = false
  getIsFirstRegistration()
  getDictOutList(1)
  if (appStore.IS_PRINT) {
    if (systemConfig.value.isMergeRegisterFee) {
      onPrint(jzbhs)
    } else {
      onPrint(jzbhs, pjhm)
    }
  }
}
// 打印
const onPrint = (jzbhs = [], pjhm = []) => {
  if (!isPrintReceipt.value) return
  if (registerState.value.ssje) {
    if (jzbhs.length > 0) {
      jzbhs.forEach(async (item, index) => {
        const { code, msg, data } = await post(systemConfig.value.isPrint, { jzbh: item, pjhm: pjhm[index] || null, sftfbs: 0 })
        if (code !== 0) return message.error(msg)
        window.openExe?.rpt(data) //调用winform打印
      })
    }
  } else {
    if (systemConfig.value.isBill) {
      if (jzbhs.length > 0) {
        jzbhs.forEach(async (item, index) => {
          const { code, msg, data } = await post(systemConfig.value.isPrint, { jzbh: item, pjhm: pjhm[index] || null, sftfbs: 0 })
          if (code !== 0) return message.error(msg)
          window.openExe?.rpt(data) //调用winform打印
        })
      }
    }
  }
}

// 判断是否是第一次挂号
const getIsFirstRegistration = async () => {
  if (systemConfig.value.isLabel) {
    const { code, data, msg } = await get('/common/patient/isFirstRegistration?br_id=' + patientState.value?.brId)
    if (code !== 0) return message.error(msg)
    if (data) {
      onPrintLabel()
    } else {
      onReset()
    }
  } else {
    onReset()
  }
}

// 打印客户标签
const onPrintLabel = async () => {
  const firstRegistration = dictOutList.value.find((item) => item.dictOutpMatterId === activeKey.value)
  if (firstRegistration?.matterName === '手术初诊') {
    const labelNumber = getSystemConfig('PRINTING_LABELS_FOR_MEDICAL_MATTERS')
    if (Number(labelNumber)) {
      for (let i = 0; i < Number(labelNumber); i++) {
        const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: patientState.value?.brId })
        if (code !== 0) return message.error(msg)
        window.openExe?.rpt(data) //调用winform打印
      }
    }
  } else {
    const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', { brId: patientState.value?.brId })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  }
  await onReset()
}

const savePatientInfo = async (onlySave = false) => {
  const idCard = patientState.value.brSfz
  if (patientState.value.brZjlx && patientState.value.brZjlx === '身份证') {
    if (idCard && idCard.length) {
      const { code: codeZjh, msg: msgZjh } = await post('/common/util/getCsrq', { sfzhm: idCard })
      if (codeZjh !== 0) return message.error(msgZjh || '身份证有误')
    }
  }
  if (patientState.value.isBrBlkh && !patientState.value.brBlkh) {
    return message.error('请填写病历号')
  }
  if (patientState.value.jksy !== 0) {
    patientState.value.jksy = patientState.value?.brId ? 2 : 1
  }
  if (Number(memberPrice.value) > registerState.value.ssje) {
    return message.error('会员卡优惠金额不能大于实收金额')
  }
  // 按断年龄是否为0，
  if (patientState.value.brAge === '0') {
    const isAgeConfirm = await cofirmModal({ title: '提示', content: '当前患者年龄为0,请确认是否真实?' })
    if (!isAgeConfirm) {
      return
    }
  }
  // 判断咨询师是否必填
  if (systemConfig.value.isCounselor && !patientState.value.brZxsName) {
    return message.error('请选择咨询师')
  }
  const { code, msg, data } = await post('/common/patient/savePatientInfo', {
    ...patientState.value,
    brAge: getAgeUnit(patientState.value.brAge).brAge || 0
  })
  patientState.value.brId = data
  if (onlySave) {
    if (code !== 0) return message.error(msg || '保存失败')
    message.success('保存成功')
    return
  }

  if (code === 0) {
    patientState.value.brId = data
    if (!registerState.value.ysje) {
      onChargeSuccess()
    } else {
      systemConfig.value.isMergeRegisterFee ? onChargeSuccess() : (chargeOpen.value = true)
    }
  } else {
    if (patientState.value?.brId) return message.error(msg)
    const isConfirm = await cofirmModal({ title: '提示', content: msg })
    if (isConfirm) {
      patientState.value.jksy = 0
      savePatientInfo()
    }
  }
}
const onReset = (activeState) => {
  // czfz: 0,
  registerState.value = { ghlbid: systemConfig.value.defaultCategoryId, czfz: 0, xxkf: false, blbf: false, oldKsdm: registerState.value.oldKsdm }
  patientState.value = { brXb: '男' }
  couponId.value = ''
  memberId.value = ''
  memberPrice.value = ''
  couponPrice.value = ''
  activeState !== 1 && getFeeList()
  getDoctorList()
  patientInfoForm.value.getMedicalRule()
  activeKey.value = getSystemConfig('OUTP_DEFAULT_VISIT_DESTINATION_CODE')
}
// 判断必填项
const isCompleted = computed(() => {
  const baseStatus =
    registerState.value.ksdm && patientState.value.brName && patientState.value.brAge && registerState.value.ghfybh && registerState.value.ghfbid
  return systemConfig.value.isCounselor ? baseStatus && patientState.value.brZxsName : baseStatus
})

const onSelectAssistant1 = (select) => {
  registerState.value.assistant1EmpId = select.empId
  registerState.value.assistant1EmpName = select.empName
}
// const onSelectAssistant2 = (select) => {
//   registerState.value.assistant2EmpId = select.empId
//   registerState.value.assistant2EmpName = select.empName
// }

watch(
  () => patientState.value.ghlbid,
  (val) => {
    onSelectDepartment(registerState.value.ksdm)
    if (val) {
      registerState.value.ghlbid = patientState.value.ghlbid
    } else {
      registerState.value.ghlbid = systemConfig.value.defaultCategoryId
    }
  }
)

const route = useRoute()
const dictMatterId = ref('') // 就诊事项id

//获取患者信息
const getPatientInfo = async () => {
  dictMatterId.value = route.query?.dictOutpMatterId
  if (route.query.id) {
    const { code, data = {} } = await get('/common/patient/getPatientInfo?br_id=' + route.query.id)
    if (code !== 0) return message.error('获取患者信息失败')
    patientState.value = { ...patientState.value, ...data } // yylsh: userInfoStore.patientInfo?.yylsh
    registerState.value.czfz = data.czfz ?? 0
    registerState.value.chargeStandardId = data.chargeStandardId
    registerState.value.ghlbid = data.ghlbid || systemConfig.value.defaultCategoryId
    patientState.value.jksy = 2
    if (data.yylsh) {
      registerState.value.ksdm = data.ksdm
      registerState.value.ksdms = [data.ksdm]
      activeKey.value = data.dictOutpMatterId
      registerState.value.memo = data.yymemo
      getDoctorList()
    }
  }
  if (route.query.id) {
    getFeeList()
  } else {
    watch(
      () => registerState.value.ghlbid,
      () => {
        getFeeList()
      }
    )
  }
}
const onClearSuit = () => {
  registerState.value.tcid = ''
  registerState.value.tcName = ''
  registerState.value.tchjje = 0
  registerState.value.tcjsje = 0
  // packRef.value?.getPackData()
}
// 获取就诊事项
const getDictOutList = async (state) => {
  const res = await post('/outp/mzdj/getDictOutpMatterNumberList')
  if (res.code !== 0) return message.error(res.msg)
  dictOutList.value = res.data
  if (state !== 1) {
    activeKey.value = getSystemConfig('OUTP_DEFAULT_VISIT_DESTINATION_CODE')
    dictMatterId.value && (activeKey.value = dictMatterId.value)
  }
}
const systemConfig = ref({})
onMounted(async () => {
  systemConfig.value = {
    isInterconnection: getSystemConfig('IS_HIS_CONNECTIVITY_PATIENT') === '1', //是否打开互联互通
    isInfoCardFee: getSystemConfig('CHARGE_INFORMATION_CARD') === '1', //收取信息卡费
    isMedicalCardFee: getSystemConfig('CHARGE_MEDICAL_RECORD_BOOK') === '1', //收取病历本费
    isCoupon: getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1', //启用挂号优惠功能
    isDisposePackage: getSystemConfig('ENABLE_OUTP_REGISTER_CHARGE_PACKAGE') === '1', //门诊挂号允许添加处置套餐
    isMergeRegisterFee: getSystemConfig('IS_MERGE_REGISTRATION_FEE') === '1', //是否合并挂号费
    isChargeStandard: getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1', //收费标准
    defaultChargeMode: getSystemConfig('REGISTERED_FEE_MODEL'), //挂号收费模式
    defaultCategoryId: getSystemConfig('REGISTER_DEFAULT_CATEGORY_CODE'), //默认挂号类别编号
    defaultDepartment: getSystemConfig('REGISTER_DEFAULT_DEPT_CODE'), //默认挂号科室编号
    isHistoryList: getSystemConfig('REGISTER_FORM_SHOW_HISTORY') === '1', //是否显示历史记录1显示0不显示
    isAssistance: getSystemConfig('IS_SHOW_REGISTER_FORM_DOCTOR_ASSISTANT ') === '1', // 是否在挂号登记页显示医助
    isLabel: getSystemConfig('IS_REGISTER_AUTO_PRINT_PATIENT_LABEL') === '1', // 0：不打印|1：自动打印
    isBill: getSystemConfig('PRINT_BILL_WHEN_FEE_IS_ZERO') === '1', // 费用为0时判断是否打印 0：不打印 1：打印
    isCounselor: getSystemConfig('IS_REQUIRED_CONSULTANT') === '1', //是否咨询师必填
    isPrint: getSystemConfig('REGISTRATION_FORM_PRINT_MODE') === '2' ? '/outp/outPrint/getRegistrationPrint' : '/outp/outPrint/getRegistrationBillPrint' // 0：通用|1：上海黑马|2：茗视光
  }
  registerState.value.ghlbid = systemConfig.value.defaultCategoryId
  registerState.value.ksdm = systemConfig.value.defaultDepartment
  registerState.value.oldKsdm = systemConfig.value.defaultDepartment
  registerState.value.ksdms = [systemConfig.value.defaultDepartment]
  getPatientInfo()
  getFeeList()
  getDepartmentList()
  getDictOutList()
})
//扫码
const onScanCode = async () => {
  setTimeout(async () => {
    if (patientState.value.brId) {
      const { code, data, msg } = await post('/outp/mzdj/getPatientRegistrationSign', { brId: patientState.value?.brId })
      if (code !== 0) return message.error(msg)
      if (data) {
        rowData.value = data
        signOpen.value = true
      }
    }
  }, 1000)
}
const onSuccessSignIn = () => {
  if (systemConfig.value.isMergeRegisterFee) {
    onPrint([rowData.value.jzbh])
  } else {
    onPrint([rowData.value.jzbh], [rowData.value.pjhm])
  }
}
const isArmy = getSystemConfig('NAVYHIS_MODE') === '1'
</script>
<style lang="less" scoped>
.border-heavy {
  border-color: var(--border-heavy-color);
}

:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
/* For demo */
:deep(.slick-slide) {
  padding-right: 50px;
  padding-left: 50px;
  overflow: hidden;
  text-align: center;
}
:deep(.slick-arrow:before) {
  display: none;
}
.cost-type {
  :deep(.ant-form-item-required) {
    padding-top: 7px;
  }
}
:deep(.ant-card-body) {
  display: flex;
  flex-direction: column;
}
</style>
